#modifyId200710211532
#modify code to only for mRNA sequence
#the assumation is that cds only have start..end format

#modifyId200712141214
#output tile modify
#>id|Moops|StartCodon|x|Cds_Length|x

#modifyId200712111134
#ADD output  path as parameter

#modifyId200712011838
#Renamed to UTR3ProEx
#3' utr extract

#modifyId20071201
#by zuofeng li
#modified for single sequence.

#this script is modified from GenbankToAnnotatedFasta.pl
#http://tiger.dbs.nus.edu.sg/microtar/files/GenbankToAnnotatedFasta.pl
#I reserved the origin function and add my own function
#zuofeng li
#Shanghai Center for  Bioinformation Technology
#2007.11.15

#!/usr/bin/perl
use strict;



my $filename = shift || die("Paste a GenBank filename on the command line.\n\n");
my $outpath = shift || die("Paste a output path without slash at the end on the command line.\n\n");
unless(open(GBFILE, "$filename"))
{
	die("can not open the file");
}
my $outfile = $outpath."3utr.fasta";

unless(open(UTRFILE, ">$outfile"))
{
	die("can not create the file!");
}

my $cdsInfo= "";
my $start = 0;
my $end = 0;
my $fullseq = "";
my $line = "";
my $title = "";
while($line=<GBFILE>)
{
if($line=~/^LOCUS/)
{
	chomp($line);
	my @field = split(/ +/,$line);
	$title = $field[1];
}


	if($line=~/^     CDS/)
	{
		chomp($line);
		$line=~s/     CDS             //;
		my @field = split(/\.\./, $line);
		$start = $field[0];
              $end = $field[1];	
			  chomp($start);
			  chomp($end);	
	}

	if($line=~/^ORIGIN/)
	{
	
		while($line=<GBFILE>)
		{	
			if($line=~/^\/\//)
			{
				last;
			}
		chomp($line);

                   $fullseq.= $line;

		}
	}
}
close(GBFILE);
$fullseq =~tr/0-9/ /;
my @field = split(//, $fullseq);
my $utr3prime = "";
my $id = 0;
for(my $i =0; $i<=$#field; $i++)
{
	if($field[$i]!~/ /)
	{
		$id++;
		if($id> $end)
		{
			$utr3prime.= $field[$i];
		}
	}
}

my $cds_length = $end -$start +1;
my $init = 0;

$utr3prime =  uc($utr3prime);
$title = ">".$title;
$title.="|Moops|StartCodon|$init|Cds_Length|$cds_length";#modifyId200712141214
print UTRFILE $title;

my @fn = split(//, $utr3prime);
for(my $i =0; $i<=$#fn; $i++)
{
	if($i%60 == 0)
	{
		$cds_length+=1+$i;
		print UTRFILE "\n$cds_length  ";
		print  UTRFILE $fn[$i];
	}
	else
	{
		print  UTRFILE $fn[$i];
	}

}

close(UTRFILE);